package com.ksvip.next.components.util.http;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.ksvip.next.components.core.exception.BusinessRuntimeException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 封装 OkHttpClient
 *
 * @since 2020/4/6
 */
public class Okhttp3ClientUtils {

    private static final OkHttpClient client;
    private static final int          HTTP_SUCCESS_CODE = 200;

    static {
        client = new OkHttpClient.Builder().connectTimeout(1, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS)
                .build();
    }

    public static String get(String url) throws IOException {
        Request request = new Request.Builder().get().url(url).build();
        return execute(request);
    }

    public static String post(String url, RequestBody requestBody) throws IOException {
        Request request = new Request.Builder().post(requestBody).url(url).build();
        return execute(request);
    }

    private static String execute(Request request) throws IOException {
        try (Response response = client.newCall(request).execute()) {
            int responseCode = response.code();
            if (responseCode == HTTP_SUCCESS_CODE) {
                ResponseBody body = response.body();
                if (body == null) {
                    return null;
                } else {
                    return body.string();
                }
            }
            throw new BusinessRuntimeException("999999", String.format("http request failed,code=%d", responseCode));
        }
    }

}
